package com.koron.css2.systemManage.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.OrgUserQueryBean;
import com.koron.css2.systemManage.bean.RoleBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoleService implements IRoleService{
	
	private static Logger log = LogManager.getLogger(RoleService.class);
	
	@Override
	public void deleteRole(String roleCode) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		RedisUtils.expire(roleCode);
		Map<String, String> param = new HashMap<String, String>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.DEL_ROLE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("删除角色失败");
		}
	}
	
	@Override
	public void addRoleUser(String roleCode, List<OrgUserBean> users) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(users == null) {
			throw new IllegalArgumentException("userCodeList 不能为空");
		}
		List<String> userCodeList = users.stream().map(t -> t.getAccount()).collect(Collectors.toList());
		Map<String, Object> data = new HashMap<>();
		data.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		data.put("roleCode", roleCode);
		data.put("userCodeList", userCodeList);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.ADD_ROLE_USER_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(data));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加角色失败");
		}
	}
	
	@Override
	public void deleteRoleUser(OrgUserBean orgUser) {
		if(orgUser == null) {
			throw new IllegalArgumentException("account 不能为空");
		}
		Map<String, Object> data = new HashMap<>();
		data.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		data.put("userCode", orgUser.getAccount());
		data.put("app", ApplicationConfig.getAppCustomerAppid());
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/deleteRoleByUser.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(data));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("刪除角色用戶失败");
		}
	}
	
	@Override
	public void deleteRoleAndUser(String roleCode, List<OrgUserBean> users) {
		if(users == null) {
			throw new IllegalArgumentException("account 不能为空");
		}
		if(roleCode == null) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		List<String> userCodeList = users.stream().map(t -> t.getAccount()).collect(Collectors.toList());
		Map<String, Object> data = new HashMap<>();
		data.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		data.put("userCodeList", userCodeList);
		data.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/deleteRoleAndUser.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(data));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("刪除角色用戶失败");
		}
	}
	
	@Override
	public void addRole(RoleBean role) {
		role.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
		role.setRoleWeight(100);
		role.setRoleStatus(0);
		if(StringUtils.isEmpty(role.getRoleName())) {
			throw new IllegalArgumentException("角色名称不能为空");
		}
		if(StringUtils.isEmpty(role.getApp())) {
			throw new IllegalArgumentException("app 不能为空");
		}
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.ADD_ROLE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(role));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加角色失败");
		}
	}

	/**
	 * 获取当前应用的所有角色
	 * @param factory
	 * @param user
	 * @return
	 */
	@Override
	public List<RoleBean> listRole(String appId){
		Map<String, String> param = new HashMap<String, String>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("app", appId);
		String url = ApplicationConfig.getAuthorityUrl() + "/permissionController/queryAllRole.htm";
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询角色列表失败");
		}
		return JsonUtils.jsonToList(json.getString("data"), RoleBean.class);
	}
	
	@Override
	public List<RoleBean> listRoleByUser(OrgUserBean user, String appId){
		if(StringUtils.isEmpty(user.getAccount())) {
			throw new IllegalArgumentException("account 不能为空");
		}
		Map<String, String> param = new HashMap<String, String>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("userCode", user.getAccount());
		param.put("app", appId);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.QUERY_USER_ROLE_URL;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询用户所属角色失败");
		}
		return JsonUtils.jsonToList(json.getString("data"), RoleBean.class);
	}
	
	@Override
	public PageInfo<OrgUserBean> listUserByRole(SessionFactory factory, String roleCode, int page , int pageCount){
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		Map<String, String> param = new HashMap<String, String>();
		param.put("tenantCode", ApplicationConfig.getAuthorityTenantCode());
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityUrl() + ApplicationConfig.QUERY_USER_ROLE;
		String result = HttpUtils.sendPostJson(url, JsonUtils.objectToJson(param));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询用户所属角色失败");
		}
		List<String> accounts = JsonUtils.jsonToList(json.getString("data"), String.class);
		if(accounts != null && accounts.size() > 0) {
			OrgUserMapper orgUserMapper = factory.getMapper(OrgUserMapper.class);
			OrgUserQueryBean orgUserQueryBean = new OrgUserQueryBean();
			orgUserQueryBean.setUserAccounts(accounts);
			PageHelper.startPage(page, pageCount);
			return new PageInfo<OrgUserBean>(orgUserMapper.selectByAccounts(orgUserQueryBean));
		}
		return new PageInfo<OrgUserBean>(new ArrayList<>());
	}
}
